package cn.plushine.controller;

import cn.plushine.pojo.*;
import cn.plushine.service.BasePOrderService;
import cn.plushine.service.BaseSOrderService;
import cn.plushine.utils.ResMapUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * 销售订单
 */
@Api(tags = "销售订单")
@Controller
@RestController
@RequestMapping("/admin/product/sOrder")
public class BaseSOrderController {

    @Autowired
    BaseSOrderService baseSOrderService;

    // 获取销售订单
    @ApiOperation(value = "获取销售订单")
    @GetMapping("/get")
    public HashMap<String, Object> get() {
        try {
            // 获取销售订单
            List<SOrder> sOrdersDB = baseSOrderService.get();

            // 货物种类（size），货物总数（sum），购货总价（total），状态判断（flag）
            HashSet<Integer> hashSet = new HashSet<Integer>();
            int sum, flag;
            BigDecimal total;
            for (SOrder sOrder : sOrdersDB) {
                hashSet.clear();
                sum = 0;
                flag = 0;
                total = BigDecimal.ZERO;
                for (SOrderItem order : sOrder.getSOrders()) {
                    hashSet.add(order.getGoodsId());
                    sum += order.getNum();
                    flag += order.getFlags();
                    total = total.add(order.getOutPrice().multiply(BigDecimal.valueOf(order.getNum())));
                }
                sOrder.setSize(hashSet.size());
                sOrder.setSum(sum);
                sOrder.setTotal(total);
                // 订单状态判断
                sOrder.setFlags(flag == 0 ? 0 : (flag == sum ? 2 : 1));
            }
            // 成功响应
            return ResMapUtils.encapsulation(200, "获取销售订单成功！", sOrdersDB);
        } catch (Exception e) {
            // 失败响应
            return ResMapUtils.encapsulation(201, "获取销售订单失败！", e.getMessage());
        }
    }

    //    // 获取货物列表
//    @ApiOperation(value = "获取货物列表")
//    @GetMapping("/getGoods")
//    public HashMap<String, Object> getGoods() {
//        try {
//            // 获取货物列表
//            List<Goods> goodsDB = baseSOrderService.getGoods();
//            // 成功响应
//            return ResMapUtils.encapsulation(200, "获取货物列表成功！", goodsDB);
//        } catch (Exception e) {
//            // 失败响应
//            return ResMapUtils.encapsulation(201, "获取货物列表失败！", e.getMessage());
//        }
//    }
//
    // 生成销售订单id
    @ApiOperation(value = "生成销售订单id")
    @GetMapping("/getId")
    public HashMap<String, Object> getId() {
        try {
            // 生成销售订单id
            String id = "XSDD" + System.currentTimeMillis();
            // 成功响应
            return ResMapUtils.encapsulation(200, "生成销售订单id成功！", id);
        } catch (Exception e) {
            // 失败响应
            return ResMapUtils.encapsulation(201, "生成销售订单id失败！", e.getMessage());
        }
    }

    // 查询货物出库价格、单位和库存
    @ApiOperation(value = "查询货物出库价格、单位和库存")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "货物id", required = true, paramType = "path", dataType = "int", example = "1")
    })
    @GetMapping("/getUnit/{id}")
    public HashMap<String, Object> getUnit(@PathVariable int id) {
        try {
            // 查询货物出库价格、单位和库存
            Goods unitDB = baseSOrderService.getUnit(id);
            // 成功响应
            return ResMapUtils.encapsulation(200, "查询货物出库价格、单位和库存成功！", unitDB);
        } catch (Exception e) {
            // 失败响应
            return ResMapUtils.encapsulation(201, "查询货物出库价格、单位和库存失败！", e.getMessage());
        }
    }

    // 添加销售订单
    @ApiOperation(value = "添加销售订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "销售订单编号", required = true, paramType = "path", dataType = "String"),
            @ApiImplicitParam(name = "salesperson", value = "创建人", required = true, paramType = "path", dataType = "int", example = "1"),
            @ApiImplicitParam(name = "date", value = "创建时间", required = true, paramType = "path", dataType = "Date"),
            @ApiImplicitParam(name = "customer", value = "客户id", required = true, paramType = "path", dataType = "int", example = "1"),
            @ApiImplicitParam(name = "sOrderItems", value = "订单内容", required = true, paramType = "body", dataType = "List<SOrderItem>")
    })
    @PostMapping("/add/{id}/{date}/{salesperson}/{customer}")
    public HashMap<String, Object> add(@PathVariable String id, @PathVariable Date date, @PathVariable int salesperson, @PathVariable int customer, @RequestBody List<SOrderItem> sOrderItems) {
        try {
            // 构造出库id
            String[] split = id.split("XSDD");
            String inputId = "CK" + split[1];

            // 添加销售订单
            baseSOrderService.addSOrder(id, date, salesperson, inputId, customer);

            // 修改货物信息
            for (SOrderItem sOrderItem : sOrderItems) {
                baseSOrderService.modify(id, sOrderItem.getOutPrice(), sOrderItem.getGoodsId(), sOrderItem.getNum());
            }

            // 成功响应
            return ResMapUtils.encapsulation(200, "添加销售订单成功！", null);
        } catch (Exception e) {
            // 失败响应
            return ResMapUtils.encapsulation(201, "添加销售订单失败！", e.getMessage());
        }
    }

    // 取消销售订单
    @ApiOperation(value = "取消销售订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "销售订单编号", required = true, paramType = "path", dataType = "String")
    })
    @DeleteMapping("/cancel/{id}")
    public HashMap<String, Object> cancel(@PathVariable String id) {
        try {
            // 取消销售订单
            baseSOrderService.cancel(id);
            // 恢复货物信息（绑定的销售订单为null）
            baseSOrderService.recover(id);
            // 成功响应
            return ResMapUtils.encapsulation(200, "取消销售订单成功！", null);
        } catch (Exception e) {
            // 失败响应
            return ResMapUtils.encapsulation(201, "取消销售订单失败！", e.getMessage());
        }
    }
}
